package me.zhanshi123.vipstorage.command.subcommand;

import me.zhanshi123.VipSystem.VipAPI;
import me.zhanshi123.VipSystem.util.Info;
import me.zhanshi123.vipstorage.Main;
import me.zhanshi123.vipstorage.MessageManager;
import me.zhanshi123.vipstorage.command.SubCommand;
import me.zhanshi123.vipstorage.util.Database;
import me.zhanshi123.vipstorage.util.StorageData;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class StoreCommand extends SubCommand {
    public StoreCommand() {
        super("store");
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(MessageManager.getString("consoleForbid"));
            return true;
        }
        Player player = (Player) sender;
        if (!player.hasPermission("vipstorage.use")) {
            sender.sendMessage(MessageManager.getString("permissionDeny"));
            return true;
        }
        String name = player.getName();
        String vipGroup = VipAPI.getInstance().getVipGroup(name);
        if (vipGroup == null) {
            sender.sendMessage(MessageManager.getString("noStoredVip"));
            return true;
        }
        Info info = Main.getVipAPI().getInfo(name);
        String vip = info.getGroup();
        long left = info.getLeft();//vip开通秒数
        if (left == -1) {
            sender.sendMessage(MessageManager.getString("noPermanentVip"));
            return true;
        }
        long now = System.currentTimeMillis();
        long seconds = (left * 1000 + info.getTime() - now) / 1000; //开通的时间+开通的秒数-现在时间
        StorageData storageData = new StorageData(name, vip, seconds, now);
        Database.getInstance().addData(storageData);
        Main.getVipAPI().removeVipWithoutCommands(name);
        sender.sendMessage(MessageManager.getString("success"));
        return true;
    }
}
